<template>
  <transition name="fade">
    <div v-if="visible" :class="['custom-message', type]" :style="positionStyle">
      <span class="message-content">{{ message }}</span>
      <span v-if="showClose" class="close-btn" @click="close">×</span>
    </div>
  </transition>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'

const props = defineProps({
  message: {
    type: String,
    required: true
  },
  type: {
    type: String,
    default: 'info'
  },
  duration: {
    type: Number,
    default: 3000
  },
  showClose: {
    type: Boolean,
    default: true
  },
  onClose: {
    type: Function,
    default: null
  }
})

const visible = ref(false)
const positionTop = ref(15) // 初始位置

const show = () => {
  visible.value = true
}

const close = () => {
  visible.value = false
  if (props.onClose) {
    props.onClose()
  }
}

onMounted(() => {
  show()
  if (props.duration > 0) {
    setTimeout(() => {
      close()
    }, props.duration)
  }
})

// 动态计算每个消息提示的位置
const positionStyle = computed(() => ({
  top: `${positionTop.value}px`,
  left: '50%',
  transform: 'translateX(-50%)'
}))

// 更新每个消息提示的位置
const updatePosition = top => {
  positionTop.value = top
}
</script>

<style scoped>
.custom-message {
  position: fixed;
  padding: 10px;
  border-radius: 8px;
  background-color: #fff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  justify-content: center; /* 增加此行以更好地排列内容 */
  z-index: 9999;
  width: fit-content; /* 根据内容自动调整宽度 */
  max-width: 90vw; /* 确保最大宽度不超过屏幕宽度的90% */
  word-wrap: break-word; /* 防止长单词溢出 */
}

.custom-message.info {
  background-color: #f4f4f5;
  color: #909399;
}

.custom-message.success {
  background-color: #f0f9eb;
  color: #67c23a;
}

.custom-message.warning {
  background-color: #fdf6ec;
  color: #e6a23c;
}

.custom-message.error {
  background-color: #fef0f0;
  color: #f56c6c;
}

.message-content {
  width: max-content;
  text-align: center;
}

.close-btn {
  background: none;
  border: none;
  cursor: pointer;
  color: inherit;
  margin-left: 5px;
  font-size: 16px;
  text-align: center;
}

/* 淡入淡出动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s ease, transform 0.5s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
  transform: translateX(-50%) scale(0.8); /* 缩小并透明 */
}

.fade-enter-to,
.fade-leave-from {
  opacity: 1;
  transform: translateX(-50%) scale(1); /* 正常大小和不透明 */
}
</style>